package org.firecloud.h5fun.controller.service;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 获取图片验证码，通过img标签src调用URL：get_verification_code<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * 注：要刷新带随机i参数调用即可<br>
 * @author fc
 */
public class GetVerificationCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int width = 183;
	private static final int height = 36;
	private static final StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyz");
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) image.getGraphics();
		g.setColor(getRandColor(150, 255));
		g.fillRect(0, 0, width, height);
		Random random = new Random();
		for (int i = 0; i < 30; i++) {
			g.setColor(getRandColor(0, 255));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = height / 2 - random.nextInt(height);
			int yl = height / 2 - random.nextInt(height);
			g.setStroke(new BasicStroke(1 + random.nextInt(2)));
			g.drawLine(x, y, x + xl, y + yl);
		}
		g.setFont(new Font("Times New Roman",Font.PLAIN,height));
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			char rand = buffer.charAt(random.nextInt(36));
			sb.append(rand);
			g.setColor(new Color(random.nextInt(200),random.nextInt(200),random.nextInt(200)));
			g.drawChars(new char[]{rand}, 0, 1, height*i+random.nextInt(25),25+random.nextInt(10));
		}
		for (int i = 0; i < 30; i++) {
			g.setColor(getRandColor(0, 255));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = height / 2 - random.nextInt(height);
			int yl = height / 2 - random.nextInt(height);
			g.setStroke(new BasicStroke(1 + random.nextInt(2)));
			g.drawLine(x, y, x + xl, y + yl);
		}
		req.getSession().setAttribute("vcode",sb.toString());
		g.dispose();
		ImageIO.write(image, "JPG", resp.getOutputStream());
	}
}
